using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

using FarseerPhysics;
using FarseerPhysics.Factories;
using FarseerPhysics.Dynamics;

namespace eTech_Physics_Sandbox
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        
        //Textures
        Texture2D texture_lineSegment;
        Texture2D texture_corner;

        World world;

        //MouseState
        //List<MouseState> stateList = new List<MouseState>(); //For use when creating lines
        MouseState lastMouseState;

        
        List<DrawableLine> drawableLines = new List<DrawableLine>(); //TODO: This is for testing, replace me -NTR
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            this.IsMouseVisible = true;
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            lastMouseState = Mouse.GetState();
            world = new World(new Vector2(0, 9.82f));
            ConvertUnits.SetScale(200f);
            DrawLine.SourceTexture = new Texture2D(GraphicsDevice, 1, 1);
            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            //Textures
            texture_lineSegment = Content.Load<Texture2D>("linesegment");
            texture_corner = Content.Load<Texture2D>("corner");
            DrawLine.SourceTexture = texture_lineSegment;
            

        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        private void makeLineFromMouse(List<MouseState> states)
        {
            List<Vector2> vectors = new List<Vector2>();
            foreach (MouseState mouseState in states)
            {
                Vector2 position = new Vector2(mouseState.X, mouseState.Y);
                vectors.Add(position);
            }

            drawableLines.Add(new DrawableLine(vectors, texture_lineSegment, texture_corner));
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            //FPS Counter
            int fps = (int)Math.Round(1 / gameTime.ElapsedGameTime.TotalSeconds);
            Window.Title = "eTech Physics Sandbox | FPS: " + fps;
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                this.Exit();

            world.Step(Math.Min((float)gameTime.ElapsedGameTime.TotalSeconds, (1f / 30f)));

            if (Mouse.GetState().LeftButton == ButtonState.Pressed && lastMouseState.LeftButton == ButtonState.Released)
            {
                drawableLines.Add(new DrawableLine(texture_lineSegment, texture_corner));
            }
            else if (Mouse.GetState().LeftButton == ButtonState.Pressed)
                drawableLines[drawableLines.Count - 1].addVertex(new Vector2(Mouse.GetState().X, Mouse.GetState().Y));
            else if (lastMouseState.LeftButton == ButtonState.Pressed)
            {
                //makeLineFromMouse(stateList);
                //stateList = new List<MouseState>();
                drawableLines[drawableLines.Count - 1].Finish(world, new Vector2(Mouse.GetState().X, Mouse.GetState().Y));
            }

            for (int i = 0; i < drawableLines.Count; i++)
                drawableLines[i].Update(gameTime);

            lastMouseState = Mouse.GetState();

                base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin();

            for (int i = 0; i < drawableLines.Count; i++)
                drawableLines[i].Draw(spriteBatch);

            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}
